import 'dart:convert';
import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:image_picker/image_picker.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class AddForumPage extends StatefulWidget {
  @override
  _AddForumPageState createState() => _AddForumPageState();
}

class _AddForumPageState extends State<AddForumPage> {
  ///发布按钮状态
  bool isSend = false;
  final TextEditingController _contentController = TextEditingController();
  final TextEditingController _titleController = TextEditingController();
  List<Widget> list;
  List<File> listPics;
  List<String> fileList;
  var picWidth = 80.0;
  String fileName = "";

  ///话题列表
  var _topicTypes = ["问答", "51单片机", "C语言", "蓝牙助手"];
  var _typeDesc = "";

  @override
  void initState() {
    super.initState();
    setState(() {
      picWidth = (Comm.screenWidth - 80) / 3.0;
    });
    print('图片宽度=$picWidth');
    _contentController.addListener(() {
      if (_contentController.text.isEmpty) {
        isSend = false;
      } else {
        isSend = true;
      }
      setState(() {});
    });
    list = List<Widget>()..add(_buildPicButton());
    listPics = List<File>();
  }

  @override
  void dispose() {
    _contentController.dispose();
    _titleController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.white, actions: <Widget>[
        FlatButton(
          onPressed: !isSend
              ? null
              : () {
                  if (listPics.length > 0) {
                    _uploadImage(listPics);
                  } else {
                    _submit();
                  }
                },
          child: Text(
            '发布',
            style:
                TextStyle(fontSize: 16, color: Theme.of(context).accentColor),
          ),
          disabledTextColor: Color(0xff999999),
        )
      ]),
      body: SingleChildScrollView(
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              _topicTitle(),
              _topicContent(),
              _choiceType(),
              _addPicture()
            ]),
      ),
    );
  }

  ///标题输入框
  Widget _topicTitle() {
    return TextField(
      style: TextStyle(fontSize: 20),
      controller: _titleController,
      decoration: InputDecoration(
          hintText: '加个标题呦~',
          hintStyle: TextStyle(color: Color(0xffBBBBBB)),
          border: InputBorder.none,
          contentPadding: EdgeInsets.all(10)),
    );
  }

  ///内容输入框
  Widget _topicContent() {
    return TextField(
      maxLines: 6,
      controller: _contentController,
      decoration: InputDecoration(
          hintText: '请开始你的表演...',
          hintStyle: TextStyle(color: Color(0xff999999)),
          border: InputBorder.none,
          contentPadding: EdgeInsets.all(10)),
    );
  }

  ///选择话题
  Widget _choiceType() {
    var type;
    if (null == _typeDesc || _typeDesc.isEmpty) {
      type = "选择话题";
    } else {
      type = _typeDesc;
    }
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.only(left: 6, right: 6, top: 2, bottom: 2),
        margin: EdgeInsets.only(left: 20, bottom: 10),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            border:
                Border.all(color: Theme.of(context).highlightColor, width: 1)),
        child: Text('#$type',
            style: TextStyle(color: Theme.of(context).accentColor)),
      ),
      onTap: () => _showTopicTypeDialog(context),
    );
  }

  ///添加图片
  Widget _addPicture() {
    return Container(
        margin: EdgeInsets.only(left: 20, right: 20),
        width: double.infinity,
        child: Wrap(children: list, spacing: 20, runSpacing: 20));
  }

  ///构建添加图片按钮
  Widget _buildPicButton() {
    return GestureDetector(
        onTap: () {
          if (listPics.length >= 3) {
            Toast.show("最多可选3张图片");
            return;
          }
          showModalBottomSheet(
              backgroundColor: Colors.transparent,
              context: context,
              builder: (builder) {
                return _choicePic();
              });
        },
        child: Container(
          width: picWidth,
          height: picWidth,
          color: Color(0xffEEEEEE),
          child: Icon(
            Icons.add,
            color: Color(0xff999999),
          ),
        ));
  }

  ///选择图片对话框
  Widget _choicePic() {
    return Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
      Container(
          width: double.maxFinite,
          margin: EdgeInsets.all(10),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(6)),
          child: Column(children: <Widget>[
            FlatButton(onPressed: _openCamera, child: Text('拍照')),
            Divider(height: 1, color: Color(0xffBBBBBB)),
            FlatButton(onPressed: _openAlbum, child: Text('从相册中选择'))
          ])),
      Container(
          width: double.maxFinite,
          margin: EdgeInsets.only(left: 10, right: 10, bottom: 10),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(6)),
          child: FlatButton(
            onPressed: () => Navigator.pop(context),
            child: Text('取消'),
          ))
    ]);
  }

  ///打开相册
  Future _openAlbum() async {
    print('打开相册');
    Navigator.pop(context);
    AssetPicker.pickAssets(context,
            maxAssets: 3 - listPics.length,
            themeColor: Theme.of(context).accentColor)
        .then((List<AssetEntity> assets) {
      assets.forEach((AssetEntity asset) async {
        File image = await asset.file;
        listPics.add(image);
        setState(() {
          list.insert(list.length - 1, _buildPhoto(image));
        });
      });
    });
  }

  ///打开相机
  void _openCamera() async {
    Navigator.pop(context);
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    listPics.add(image);
    setState(() {
      list.insert(list.length - 1, _buildPhoto(image));
    });
  }

  ///构建图片
  Widget _buildPhoto(File image) {
    return Stack(
        overflow: Overflow.visible,
        alignment: Alignment(0.9, -0.9),
        children: <Widget>[
          Container(
              width: picWidth,
              height: picWidth,
              child: Image.file(image,
                  width: picWidth, height: picWidth, fit: BoxFit.cover)),
          GestureDetector(
              onTap: () {
                var index = listPics.indexOf(image);
                setState(() {
                  listPics.removeAt(index);
                  list.removeAt(index);
                });
              },
              child: Container(
                  width: 18,
                  height: 18,
                  decoration: BoxDecoration(
                      color: Color(0x7f000000),
                      borderRadius: BorderRadius.circular(9)),
                  child: Icon(Icons.clear, color: Colors.white, size: 12)))
        ]);
  }

  ///选择话题类型对话框
  _showTopicTypeDialog(BuildContext context) {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("请选择话题"),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: _topicTypes
                  .map((item) => Builder(
                        builder: (context) {
                          return RadioListTile(
                            value: item,
                            groupValue: _typeDesc,
                            title: Text(item),
                            onChanged: (value) {
                              setState(() {
                                _typeDesc = value;
                              });
                              Navigator.pop(context);
                            },
                          );
                        },
                      ))
                  .toList(),
            ),
          );
        });
  }

  ///上传图片
  Future _uploadImage(List<File> files) async {
    CancelFunc cancelFunc = Toast.loading("上传中...");
    Http.upload(Api.URL_UPLOADS, files, successCallBack: (data) {
      Toast.show("上传成功");
      cancelFunc();
      print("上传结果：" + data);
      jsonDecode(data).forEach((item) {
        fileName = "$fileName${item["path"]},";
      });
      if (fileName.endsWith(",")) {
        fileName = fileName.substring(0, fileName.length - 1);
      }
      _submit();
    }, errorCallBack: (errorMsg) {
      Toast.show(errorMsg);
      cancelFunc();
    });
  }

  ///发布话题
  void _submit() async {
    if (null == _typeDesc || _typeDesc.isEmpty) {
      Toast.show("请选择话题分类");
      return;
    }
    CancelFunc cancelFunc = Toast.loading("发布中...");
    String title = _titleController.text;
    String content = _contentController.text;
    Map<String, String> map = Map();
    map['content'] = content;
    if (title.isNotEmpty) {
      map['title'] = title;
    }
    map["typeDesc"] = _typeDesc;
    if (fileName.isNotEmpty) {
      map["imageUrls"] = fileName;
    }
    Http.post(Api.URL_TOPIC_ADD, params: map, successCallBack: (data) {
      Toast.show('发布成功');
      cancelFunc();
      Navigator.of(context).pop();
    }, errorCallBack: (msg) {
      Toast.show(msg);
      cancelFunc();
    });
  }
}
